<template>
  <div class="tournament_list">
    <nut-navbar class="navbar" z-index="5" :clickable="false" fixed safe-area-inset-top>
      <template #content>
        <span>{{ introduction.tournm_name }}</span>
      </template>
      <template #left>
        <img src="/imgs/club/arrow_left.png" alt="" @click="router.go(-1)" class="arrow_left" />
      </template>
      <template #right>
        <!-- <span @click="onSubmitCreate" class="save">保存</span> -->
      </template>
    </nut-navbar>
    <nut-tabs @change="tabChange" v-model="state.agentId" title-scroll title-gutter="10" v-if="gameTabList">
      <nut-tab-pane :title="item.name" :pane-key="item.id" v-for="item in gameTabList" :key="item.id">
        <div class="list_con" :style="contentStyle()">
          <template v-if="item.id == 1">
          <!-- 轮播 -->
          <nut-swiper
            :init-page="0"
            :auto-play="3000"
            pagination-visible
            pagination-color="#426543"
            pagination-unselected-color="#808080"
            style="height: 124px"
            >
            <nut-swiper-item v-for="(item, index) in list" :key="index">
              <img :src="item" alt="" class="imgs" draggable="false" />
            </nut-swiper-item>
          </nut-swiper>
          <!-- 比赛信息 -->
          <TournamentCard :tournaments="tournamentList" />
          <!-- 结果信息 -->
          <InfoCard :introduction="introduction" />
          <!-- 富文内容 -->
          <RichTextContent :introduction="introduction" />
          </template>
          <template v-if="item.id == 2">
            <!-- 排行榜 -->
            <nut-infinite-loading v-model="infinityValue" load-more-txt=" "
            :has-more="hasMore" @load-more="onLoadRankings">
              <nut-empty v-if="rankingsData.length == 0" :description="t('nomore_data')"></nut-empty>
              <RankingTable v-else :rankingsData="rankingsData" :roomId="room_id" />
            </nut-infinite-loading>
          </template>
          <template v-if="item.id == 3">
            <!-- 盲注 -->
            <nut-infinite-loading v-model="infinityValue" load-more-txt=" "
            :has-more="hasMore" @load-more="onLoadBlind">
              <nut-empty v-if="rankingsData.length == 0" :description="t('nomore_data')"></nut-empty>
              <BetTable v-else :blindData="blindData" :roomId="room_id" />
            </nut-infinite-loading>
          </template>
        </div>
      </nut-tab-pane>
    </nut-tabs>
    <!-- 分享按钮 -->
    <div class="share_button" v-if="introduction.tournament_state ===  0 || introduction.tournament_state ===  1"  @click="onClickShare">
      <span>{{t('share')}}</span>
    </div>
    <!-- 已报名按钮 -->
    <div class="share_button enter" v-if="introduction.tournament_state ===  2"  @click="onClickEnter">
      <div>
        <p class="enter_title">{{t('club_page_ybm')}}</p>
        <p class="enter_con">{{t('club_page_bsq15')}}</p>
      </div>
    </div>
    <!-- 进入比赛按钮 -->
    <div class="share_button" v-if="introduction.tournament_state ===  3">
      <span>{{t('club_page_jrbs')}}</span>
    </div>
    <!-- 分享弹窗 -->
    <ShareModal v-model:visible="visible" :id="room_id" :type="2" @updata="handleUpdate" />

    <!-- 比赛前10分钟弹窗 -->
    <Modal v-model:visible="isShowTime" :title="t(club_title)" @close="">
      <div class="popup_body">
        <div class="info">
          <p>{{t('club_page_ybmts10')}}</p>
        </div>
        <div class="submit_btn">
          <Btn height="44px" width="200px" class="submit" @click="submitAc">{{ t('btnCfg_1') }}</Btn>
        </div>
      </div>
    </Modal>

    <!-- 报名成功弹窗 -->
    <Modal v-model:visible="isShowWin" :title="t(club_title)" @close="">
      <div class="popup_body">
        <div class="info">
          <p>{{t('club_page_ybmljjr')}}</p> 
          <p>{{t('club_page_djs')}}<span>{{ formattedTime }}</span>{{t('club_page_autoadd')}}</p>
        </div>
        <div class="submit_btn">
          <Btn height="44px" width="200px" class="submit" @click="enterNow">{{t('club_page_ljadd')}}</Btn>
          <Btn height="44px" width="200px" class="submit" @click="waitEnter">{{t('club_page_ddjr')}}</Btn>
        </div>
      </div>
    </Modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed, watch } from "vue";
import {  useRouter } from "vue-router";
const router = useRouter();

import TournamentCard from "../components/tournamentCard.vue";
import InfoCard from "../components/infoCard.vue";
import RichTextContent from "../components/richTextContent.vue";
import RankingTable from "../components/rankingTable.vue";
import BetTable from "../components/betTable.vue";
import ShareModal from '../components/shareModal.vue'

import PKwebsocket from "@/lolo/Ws";
import { NetPacket } from "@/netBase/NetPacket";

import { storeToRefs } from "pinia";
import pinia from "@/store/index";
import { User } from "@/store/user";
const { appHeight } = storeToRefs(User(pinia));

import { useRoute } from "vue-router";
const route = useRoute();
import { useI18n } from "vue-i18n";
const { t } = useI18n();

/**
 * 状态对应数字含义：
 * 0: 未报名 not-started
 * 1: 延迟报名 delayed
 * 2: 已报名-未开始 enter
 * 3: 已报名-已开始/进行中 active
 * 4: 已暂停 paused
 * 5: 已结束 ended
 */

const room_id = ref(0) // 房间ID

const state = reactive({
  // 1为简介
  agentId: 1,
})

const infinityValue = ref(false);
const hasMore = ref(true);
const params: any = reactive({
  // 参数
  pageSize: 25,
  page: 1,
});


const introduction = ref<any>({})

const visible = ref(false)

const isShowTime = ref(false);
const isShowWin = ref(false);
const club_title = ref(t('tip'));

const countdownTime = ref(10); // 剩余时间（秒）
const interval = ref<any>(null); // 定时器引用

const gameTabList = reactive([
  {
    id: 1,
    name: t('club_page_jjie'),
  },
  {
    id: 2,
    name: t('club_page_phb'),
  },
  {
    id: 3,
    name: t('club_page_mbet'),
  }
]);

const list = ref([
  'https://storage.360buyimg.com/jdc-article/NutUItaro34.jpg',
  'https://storage.360buyimg.com/jdc-article/NutUItaro2.jpg',
  'https://storage.360buyimg.com/jdc-article/welcomenutui.jpg',
  'https://storage.360buyimg.com/jdc-article/fristfabu.jpg'
])

// 赛事列表数据
const tournamentList = ref<any>([]);

const contentStyle = () => {
  return window.matchMedia("(display-mode: standalone)").matches ||
    window.navigator.standalone
    ? { height: `calc(${appHeight.value}px - 180px)` }
    : { height: `calc(${appHeight.value}px - 180px)` };
};

const tabChange = (item: any) => {
  state.agentId = Number(item.paneKey)
  if(item.paneKey == 1) {
    getTournamentIntroduction()
  } else if (item.paneKey == 2) {
    getTournamentRankings()
  } else if (item.paneKey == 3) {
    getTournamentBlind()
  }
}

// 获取赛事简介
const getTournamentIntroduction = () => {
  const req = NetPacket.req_tournament_introduction();
  req.room_id = Number(room_id.value)
  PKwebsocket.instance.send(req, true, {
    callbackName: "msg_notify_tournament_introduction",
    callback: getTournamentIntroductionHandle,
  });
};
// 赛事简介返回
const getTournamentIntroductionHandle = (res: any) => {
  tournamentList.value = [
    {
      'game_type': res.game_type,
      'tournm_name': res.tournm_name,
      'bonus': res.bonus,
      'begin_time': res.begin_time,
      'end_time': res.end_time,
      'need_chip': res.need_chip,
      'apply_count': res.apply_count,
      'tournm_state': res.tournament_state,
      'countdown': res.downcount,
      'room_id': res.room_id,
      'tournm_logo': res.tournm_logo,
    }
  ]
  introduction.value = res
};

const rankingsData = ref<any>([])
// 获取排行榜
const getTournamentRankings = () => {
  const req = NetPacket.req_tournament_rankings();
  req.room_id = Number(room_id.value)
  req.page = params.page
  // req.pageSize = params.pageSize
  PKwebsocket.instance.send(req, true, {
    callbackName: "msg_notify_tournament_rankings",
    callback: getTournamentRankingsHandle,
  });
};
// 排行榜返回
const getTournamentRankingsHandle = (res: any) => {
  console.log('res', res)
  rankingsData.value = [...rankingsData.value, ...res.ranking_info];
};

const blindData = ref<any>([])
// 获取盲注列表
const getTournamentBlind = () => {
  const req = NetPacket.req_tournament_blind();
  req.room_id = Number(room_id)
  req.page = params.page
  // req.pageSize = params.pageSize
  PKwebsocket.instance.send(req, true, {
    callbackName: "msg_notify_tournament_blind",
    callback: getTournamentBlindHandle,
  });
};
// 盲注列表返回
const getTournamentBlindHandle = (res: any) => {
  console.log('res', res)
  blindData.value = [...blindData.value, ...res.blind_info];
};

// 分享
const onClickShare = () => {
  visible.value = true
  // const req = NetPacket.req_tournament_events_share();
  // req.room_id = Number(room_id.value)
  // PKwebsocket.instance.send(req, true, {
  //   callbackName: "msg_notify_tournament_events_share",
  //   callback: onClickShareHandle,
  // });
}
// 分享返回
// const onClickShareHandle = (res: any) => {
//   visible.value = true
//   if(res.result === 0) {
//     visible.value = true
//     getTournamentIntroduction()
//   }
// };

const handleUpdate = (result: any) => {
  console.log('result', result)
  if(result == 0) {
    getTournamentIntroduction()
  } else {

  }
  
}

const onClickEnter = () => {
  if(introduction.value.downcount < 600) {
    isShowWin.value = true
  } else {
    isShowTime.value = true
  }
  
}

const submitAc = () => {
  isShowTime.value = false
}

//立即进入
const enterNow = () => {
  isShowWin.value = false
  if (interval.value) clearInterval(interval.value);
};

// 等等进入
const waitEnter = () => {
  isShowWin.value = false
  if (interval.value) clearInterval(interval.value);
}

// 格式化倒计时为 HH:mm:ss
const formattedTime = computed(() => {
  const hours = String(Math.floor(countdownTime.value / 3600)).padStart(2, "0");
  const minutes = String(Math.floor((countdownTime.value % 3600) / 60)).padStart(2, "0");
  const seconds = String(countdownTime.value % 60).padStart(2, "0");
  return `${hours}:${minutes}:${seconds}`;
});

 // 启动倒计时
const startCountdown = () => {
  if (interval.value) clearInterval(interval.value); // 清除之前的定时器
    interval.value = setInterval(() => {
    if (countdownTime.value > 0) {
      countdownTime.value -= 1;
    } else {
      clearInterval(interval.value); // 倒计时结束，停止计时器
    }
  }, 1000);
};


watch(
  () => countdownTime.value,
  (newVal) => {
    countdownTime.value = newVal == -1 ? 0 : newVal; // 设置初始倒计时时间
    if (countdownTime.value > 0) {
      startCountdown();
    }
  },
  { immediate: true }
);


const onLoadRankings = () => {
  params.page++;
  getTournamentRankings()
};
const onLoadBlind = () => {
  params.page++;
  getTournamentBlind()
};

// watch(
//   () => props.roomId,
//   (newId) => {
//     console.log('newId', newId)
//   },
//   { immediate: true }
// );

onMounted(() => {
  const { roomId } = route.query;
  room_id.value = Number(roomId)
  getTournamentIntroduction()
});
</script>

<style scoped lang="scss">
.tournament_list {
  
  .arrow_left {
    width: 24px;
    height: 24px;
  }
  
  .imgs{
    height: 124px;
    width: 347px;
    
  }

  :deep(.nut-swiper) {
    width: 347px;
    border-radius: 8px;
    margin: 0 auto 10px;
  }

  :deep(.nut-tabs__titles) {
    height: 36px;
  }

  .list_con {
    overflow: auto;
  }
  // 分享按钮样式
  .share_button {
    position: fixed;
    bottom: 14px;
    left: 50%; 
    transform: translateX(-50%);
    z-index: 99px;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 319px;
    height: 44px;
    margin: 0 auto;
    border-radius: 8px;
    background: linear-gradient(180deg, #5567FF 0%, #9E1EFF 100%);
    box-shadow: 0.5px 0.5px 1px 0px #9B9EFF inset;

    span {
      color: #FFF;
      text-align: center;
      font-size: 14px;
      font-weight: 500;
    }
  }
  .enter {
    p {
      color: #FFF;
      text-align: center;
      font-family: "PingFang SC";
      font-size: 14px;
      font-style: normal;
      font-weight: 500;
    }
    .enter_con {
      font-size: 12px;
    }
  }
}
.popup_body {
  color: #fff;
  padding: 10px;

  .info {
    margin: 24px 0;
    p {
      color: #FFF;
      text-align: center;
      font-family: "PingFang SC";
      font-size: 14px;
      font-style: normal;
      font-weight: 500;
      line-height: 21px; /* 150% */
      span {
        color: #F49A24;
      }
    }
  }
  :deep(.nut-input) {
    background: rgba(29, 14, 74, 1);
    box-shadow: 0px 4px 4px 0px rgba(0, 0, 0, 0.25) inset;
    border-radius: 8px;
    border-bottom: 0;
    padding: 10px;
  }
  .submit_btn {
    margin: 20px;
    display: flex;
    justify-content: center;
  }
}
</style>
